<template>
  <ContentWrap>
    <!-- 搜索工作栏：保持不变 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="航机员" prop="flightCrew">
        <el-input
          v-model="queryParams.flightCrew"
          placeholder="请输入航机员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港航班" prop="inboundFlight">
        <el-input
          v-model="queryParams.inboundFlight"
          placeholder="请输入进港航班"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="预落时间" prop="preLandingTime">
        <el-input
          v-model="queryParams.preLandingTime"
          placeholder="请输入预落时间(HHmm)"
          clearable
          @input="handleTimeInput('preLandingTime', $event)"
          @blur="handleTimeBlur('preLandingTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="实落时间" prop="inboundTime">
        <el-input
          v-model="queryParams.inboundTime"
          placeholder="请输入实落时间(HHmm)"
          clearable
          @input="handleTimeInput('inboundTime', $event)"
          @blur="handleTimeBlur('inboundTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-input
          v-model="queryParams.depTime"
          placeholder="请输入起飞时间(HHmm)"
          clearable
          @input="handleTimeInput('depTime', $event)"
          @blur="handleTimeBlur('depTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="queryParams.recordDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择记录日期"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 获取最新
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleSyncQuarter"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 同步季度计划
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:schedule-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 列设置按钮 -->
        <el-button type="primary" plain @click="handleOpenColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：保持虚拟化表格 -->
  <ContentWrap>
    <div style="height: 62vh">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
            :row-class="tableRowClassName"
            :row-height="70"
          />
        </template>
      </el-auto-resizer>
    </div>
  </ContentWrap>

  <!-- 列设置弹窗（保留原始逻辑） -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="mb-4 flex justify-between items-center">
      <span>拖拽调整列顺序</span>
    </div>
    <div style="text-align: center">
      <el-transfer
        v-model="tempSelectedColumnProps"
        :data="allColumnsForTransfer"
        filterable
        :titles="['可选列', '已选列']"
        :button-texts="['移除', '选中']"
        class="mb-4"
      />
    </div>
    <div v-if="tempSelectedColumns.length > 0">
      <el-card>
        <template #header>已选列顺序</template>
        <div class="draggable-list">
          <div
            v-for="(column, index) in tempSelectedColumns"
            :key="column.prop"
            class="draggable-item flex items-center justify-between p-3 border rounded-lg cursor-move bg-white transition-all duration-200 hover:shadow-md"
            @mousedown="startDrag(index, $event)"
            :style="{
              transform: isDragging && dragIndex === index ? 'scale(1.02)' : 'none',
              opacity: isDragging ? (dragIndex === index ? '0.8' : '0.5') : '1',
              'background-color': isDragging && dragOverIndex === index ? '#f0f7ff' : 'white',
              'border-color': isDragging && dragOverIndex === index ? '#409eff' : '#dcdfe6'
            }"
          >
            <div class="flex items-center space-x-3">
              <el-icon
                class="el-icon-rank text-gray-400 cursor-move hover:text-blue-500 transition-colors"
              >
                <Rank />
              </el-icon>
              <span class="font-medium">{{ column.label }}</span>
            </div>
            <div class="flex items-center space-x-2">
              <el-tooltip :content="`列宽度: ${column.width || 120}px`" placement="top">
                <el-icon class="text-gray-400 hover:text-blue-500 cursor-pointer transition-colors">
                  <Monitor />
                </el-icon>
              </el-tooltip>
              <el-tooltip :content="`类型: ${column.type || '文本'}`" placement="top">
                <el-icon
                  class="text-gray-400 hover:text-green-500 cursor-pointer transition-colors"
                >
                  <InfoFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 数量编辑弹窗 -->
  <el-dialog
    title="编辑数量信息"
    v-model="quantityDialogVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form ref="quantityFormRef" :model="currentRow" label-width="120px">
      <el-form-item label="销售数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewSaleQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassSaleQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassSaleQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassSaleQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="配餐数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="quantityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleQuantitySave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件（完全保留） -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <ProduceRecordForm ref="formRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, nextTick, watch, h } from 'vue'
import { ElTableV2 } from 'element-plus'
import type { Column } from 'element-plus'
import {
  ElTag,
  ElInput,
  ElButton,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon,
  ElTooltip,
  ElDialog,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol
} from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Setting,
  DArrowRight,
  Rank,
  Monitor,
  InfoFilled,
  Timer
} from '@element-plus/icons-vue'

// 保留原始所有导入
import { dateFormatter, formatDate, formatPast } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import { DICT_TYPE } from '@/utils/dict'

/** 基础配置（保留原始逻辑） */
defineOptions({ name: 'ScheduleRecordAst' })
const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<ScheduleRecordVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000,
  flightNo: undefined,
  depTime: undefined,
  flightCrew: undefined,
  inboundFlight: undefined,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined,
  recordDate: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const columnSettingVisible = ref(false)

// 数量编辑弹窗相关
const quantityDialogVisible = ref(false)
const currentRow = ref<Partial<ScheduleRecordVO>>({})
const quantityFormRef = ref()

/** 生产状态（保留原始） */
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

/** 工具函数（保留原始） */
const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) return '未开始'
  const numStatus = Number(statusValue)
  const matched = pstatusList.find(item => item.value === numStatus)
  return matched ? matched.label : '未开始'
}

const formatTimeArray = (timeArr: any[]) => {
  if (!Array.isArray(timeArr) || timeArr.length !== 2) return ''
  const hour = String(timeArr[0]).padStart(2, '0')
  const minute = String(timeArr[1]).padStart(2, '0')
  return `${hour}:${minute}`
}

const normalizeTimeFormat = (timeValue: any): string => {
  if (!timeValue) return ''
  if (Array.isArray(timeValue) && timeValue.length === 2) {
    return formatTimeArray(timeValue)
  }
  if (typeof timeValue === 'string') {
    if (/^\d{2}:\d{2}$/.test(timeValue)) return timeValue
    if (/^\d{4}$/.test(timeValue)) {
      return `${timeValue.slice(0,2)}:${timeValue.slice(2,4)}`
    }
  }
  return ''
}

const formatTimeString = (timeString: string): string | null => {
  if (timeString.includes(':')) return timeString
  if (!/^\d{4}$/.test(timeString)) return null
  const hours = parseInt(timeString.slice(0,2))
  const minutes = parseInt(timeString.slice(2,4))
  if (hours >=0 && hours <24 && minutes >=0 && minutes <60) {
    return `${String(hours).padStart(2,'0')}:${String(minutes).padStart(2,'0')}`
  }
  return null
}

const formatDisplayTime = (timeString: string | undefined): string | null => {
  if (!timeString) return null
  return formatTimeString(timeString)
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

// 保留数量列判断（用于弹窗编辑）
const isNumberColumn = (prop: string): boolean => {
  return ['crewQty','bussClassQty', 'premEcoClassQty', 'ecoClassQty','crewSaleQty','bussClassSaleQty','premEcoClassSaleQty','ecoClassSaleQty'].includes(prop)
}

const getColumnNameByProp = (prop: string): string => {
  const column = allColumns.find(col => col.prop === prop)
  return column?.label || prop
}

/** 业务逻辑函数（保留原始） */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getScheduleRecordPage(queryParams)
    list.value = data.list || []
    list.value.forEach(item => {
      item._original = JSON.parse(JSON.stringify(item))
      item.inboundTime = normalizeTimeFormat(item.inboundTime)
      item.preLandingTime = normalizeTimeFormat(item.preLandingTime)
      item.depTime = normalizeTimeFormat(item.depTime)
      item.formattedOriginal = {
        inboundTime: item.inboundTime || '',
        preLandingTime: item.preLandingTime || '',
        depTime: item.depTime || '',
        machineNo: item.machineNo || '',
        airportStands: item.airportStands || '',
        inboundFlight: item.inboundFlight || '',
        remarks: item.remarks || '',
        bussClassQty: item.bussClassQty || '',
        crewSaleQty: item.crewSaleQty || '',
        bussClassSaleQty: item.bussClassSaleQty || '',
        premEcoClassSaleQty: item.premEcoClassSaleQty || '',
        ecoClassSaleQty: item.ecoClassSaleQty || '',
        crewQty: item.crewQty || '',
        premEcoClassQty: item.premEcoClassQty || '',
        ecoClassQty: item.ecoClassQty || '',
        specialRemarks: item.specialRemarks || ''
      }
    })
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  if (formRef.value && flightNo) formRef.value.openFlightNo(type, flightNo)
}

const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  if (formAddRef.value && flightNo) formAddRef.value.openAdd('create', flightNo, recordDate)
}

const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleColumnTimeBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && /^\d{2}:\d{2}$/.test(current)) {
    await handleFieldChange(row)
    return
  }

  if (current && (current.length !==4 || !/^\d{4}$/.test(current))) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`)
    row[prop] = original
    return
  }

  if (current) {
    const formatted = formatTimeString(current)
    if (formatted) {
      if (formatted === original) {
        row[prop] = formatted
        return
      }
      row[prop] = formatted
      await handleFieldChange(row)
    } else {
      message.error('请输入有效的时间格式(HHmm)')
      row[prop] = original
    }
  } else {
    if (original !== '') await handleFieldChange(row)
  }
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  // 先过滤非数字字符，再截取前9位以限制最大长度
  const numericValue = value.replace(/[^0-9]/g, '');
  row[prop] = numericValue.slice(0, 9);
};
const handleNumberBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) <0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return
  await handleFieldChange(row)
}

const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }

    const hasChange = Object.keys(row).some(key => {
      if (key === '_original' || key === 'formattedOriginal') return false
      const original = row.formattedOriginal[key] || ''
      const current = row[key] || ''
      if (isTimeColumn(key)) return original !== current
      if (isNumberColumn(key)) return String(original) !== String(current)
      return original !== current
    })

    if (!hasChange) return

    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      crewSaleQty: row.crewSaleQty ? Number(row.crewSaleQty) : undefined,
      bussClassSaleQty: row.bussClassSaleQty ? Number(row.bussClassSaleQty) : undefined,
      premEcoClassSaleQty: row.premEcoClassSaleQty ? Number(row.premEcoClassSaleQty) : undefined,
      ecoClassSaleQty: row.ecoClassSaleQty ? Number(row.ecoClassSaleQty) : undefined,
      crewQty: row.crewQty ? Number(row.crewQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO
    const res = await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(res !== 'success' ? res : '更新成功')

    row._original = JSON.parse(JSON.stringify(row))
    row.formattedOriginal = {
      inboundTime: row.inboundTime || '',
      preLandingTime: row.preLandingTime || '',
      depTime: row.depTime || '',
      machineNo: row.machineNo || '',
      airportStands: row.airportStands || '',
      inboundFlight: row.inboundFlight || '',
      remarks: row.remarks || '',
      bussClassQty: row.bussClassQty || '',
      crewSaleQty: row.crewSaleQty || '',
      bussClassSaleQty: row.bussClassSaleQty || '',
      premEcoClassSaleQty: row.premEcoClassSaleQty || '',
      ecoClassSaleQty: row.ecoClassSaleQty || '',
      crewQty: row.crewQty || '',
      premEcoClassQty: row.premEcoClassQty || '',
      ecoClassQty: row.ecoClassQty || '',
      specialRemarks: row.specialRemarks || ''
    }
  } catch (err) {
    console.error('更新失败:', err)
    message.error('更新失败，请重试')
    await getList()
  }
}

// 数量编辑弹窗确认保存
const handleQuantitySave = async () => {
  try {
    if (!currentRow.value.id) {
      message.error('数据无效')
      return
    }
    // 深拷贝当前行数据用于比较
    const tempRow = JSON.parse(JSON.stringify(currentRow.value)) as ScheduleRecordVO
    // 调用通用更新方法
    await handleFieldChange(tempRow)
    // 关闭弹窗
    quantityDialogVisible.value = false
    // 刷新列表
    await getList()
  } catch (err) {
    console.error('数量更新失败:', err)
    message.error(t('common.updateFail'))
  }
}

const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    if (row.pstatus === newStatus) return
    await ScheduleRecordApi.updateScheduleRecord({ id: row.id, pstatus: newStatus })
    row.pstatus = newStatus
    message.success(t('common.updateSuccess'))
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('状态更新失败:', err)
  }
}

const importFormRef = ref()
const handleImportLog = () => importFormRef.value?.open()

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ScheduleRecordApi.exportScheduleRecord(queryParams)
    download.excel(data, '配送管理-调度生产记录.xls')
  } catch {} finally {
    exportLoading.value = false
  }
}

const handleSyncQuarter = async () => {
  try {
    await message.exportConfirm('同步季度计划会重置今日计划和生产计划，是否同步？')
    exportLoading.value = true
    await ScheduleRecordApi.syncQuarterPlan()
    message.success('同步成功')
    await getList()
  } catch {} finally {
    exportLoading.value = false
  }
}

/** 列配置逻辑（整合数量列） */
interface TableColumn {
  prop: string
  label: string
  width?: number
  editable?: boolean
  editWidth?: number
  type?: string
}

const TABLE_TYPE = 'ast'
const allColumns: TableColumn[] = [
  { prop: 'inboundFlight', label: '进港航班', width: 150, editable: true, editWidth: 120, type: '文本' },
  { prop: 'flightNo', label: '航班号', width: 120, type: '文本' },
  { prop: 'route', label: '航线', width: 180, type: '文本' }, // 新增航线列
  { prop: 'machineNo', label: '机号', width: 140, editable: true, editWidth: 110, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'preLandingTime', label: '预落时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'inboundTime', label: '实落时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  { prop: 'recordDate', label: '日期', width: 120, type: '日期' },
  { prop: 'airportStands', label: '机位', width: 130, editable: true, editWidth: 100, type: '文本' },
  { prop: 'remarks', label: '备注', width: 200, editable: true, editWidth: 200, type: '文本' },
  // 整合数量相关列
  { prop: 'quantity', label: '数量', width: 300, type: '复合' },
  { prop: 'specialRemarks', label: '特殊说明', width: 200, editable: true, editWidth: 200, type: '文本' },
  { prop: 'aircraftType', label: '机型', width: 120, type: '文本' },
  { prop: 'airlineComp', label: '所属公司', width: 120, type: '状态' },
  { prop: 'airlinePattern', label: '航班类型', width: 120, type: '状态' },
  { prop: 'company', label: '所属公司', width: 120, type: '文本' },
  { prop: 'createTime', label: '创建时间', width: 180, type: '时间' },
  { prop: 'pstatus', label: '生产状态', width: 120, type: '状态' }
]

// 列设置拖拽逻辑（保留原始）
const backendColumnSettings = ref<{ prop: string; sort: number; visible?: boolean }[]>([])
const selectedColumnProps = ref<string[]>([])
const selectedColumns = ref<TableColumn[]>([])
const tempSelectedColumnProps = ref<string[]>([])
const tempSelectedColumns = ref<TableColumn[]>([])
const isDragging = ref(false)
const dragIndex = ref(-1)
const dragOverIndex = ref(-1)
const dragStartY = ref(0)

const fetchColumnSettings = async () => {
  try {
    const res = await ScheduleRecordApi.getTableitem({ tableType: TABLE_TYPE })
    if (!res || !res.props || !Array.isArray(res.props)) return []
    return res.props
      .filter(setting => setting && typeof setting.prop === 'string' && setting.prop.trim() && setting.visible !== false)
      .map(setting => ({
        prop: setting.prop.trim(),
        sort: typeof setting.sort === 'number' ? setting.sort : 0,
        visible: setting.visible !== false
      }))
  } catch (err) {
    return []
  }
}

const initColumnSettings = async () => {
  try {
    const backend = await fetchColumnSettings()
    if (backend.length > 0) {
      const sorted = [...backend].sort((a, b) => a.sort - b.sort)
      const validProps = sorted
        .map(s => s.prop)
        .filter(prop => allColumns.some(col => col.prop === prop))
      selectedColumnProps.value = validProps
    } else {
      selectedColumnProps.value = allColumns.slice(0,8).map(col => col.prop)
    }
    updateSelectedColumns()
  } catch (err) {
    selectedColumnProps.value = allColumns.slice(0,8).map(col => col.prop)
    updateSelectedColumns()
  }
}

const updateSelectedColumns = () => {
  const cols = selectedColumnProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter((col): col is TableColumn => !!col)
  selectedColumns.value = []
  nextTick(() => selectedColumns.value = cols)
}

const updateTempSelectedColumns = () => {
  const cols = tempSelectedColumnProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter((col): col is TableColumn => !!col)
  tempSelectedColumns.value = []
  nextTick(() => tempSelectedColumns.value = cols)
}

// 列设置打开函数（供搜索栏按钮调用）
const handleOpenColumnSetting = () => {
  tempSelectedColumnProps.value = [...selectedColumnProps.value]
  updateTempSelectedColumns()
  columnSettingVisible.value = true
}

const saveColumnSettings = async () => {
  try {
    const data = {
      tableType: TABLE_TYPE,
      props: tempSelectedColumns.value.map((col, idx) => ({
        prop: col.prop,
        label: col.label,
        width: col.width || 120,
        visible: true,
        sort: idx + 1,
        editable: col.editable || false,
        editWidth: col.editWidth || 100,
        type: col.type || '文本'
      }))
    }
    await ScheduleRecordApi.updateTableitem(data)
    selectedColumnProps.value = [...tempSelectedColumnProps.value]
    selectedColumns.value = [...tempSelectedColumns.value]
    await getList()
    columnSettingVisible.value = false
  } catch (err) {
    message.error('列设置保存失败')
  }
}

const startDrag = (index: number, e: MouseEvent) => {
  isDragging.value = true
  dragIndex.value = index
  dragStartY.value = e.clientY
  const onMove = (moveE: MouseEvent) => onDragMove(moveE)
  const onUp = () => stopDrag(onMove, onUp)
  const onLeave = () => stopDrag(onMove, onUp)
  document.addEventListener('mousemove', onMove)
  document.addEventListener('mouseup', onUp)
  document.addEventListener('mouseleave', onLeave)
  e.preventDefault()
}

const onDragMove = (e: MouseEvent) => {
  if (!isDragging.value || dragIndex.value === -1) return
  const item = document.elementFromPoint(e.clientX, e.clientY)?.closest('.draggable-item')
  if (!item) return
  const items = Array.from(document.querySelectorAll('.draggable-item'))
  const currentIdx = items.indexOf(item)
  if (currentIdx === -1 || currentIdx === dragIndex.value) return
  dragOverIndex.value = currentIdx
  if (Math.abs(e.clientY - dragStartY.value) > 20) {
    const newCols = [...tempSelectedColumns.value]
    const [removed] = newCols.splice(dragIndex.value, 1)
    newCols.splice(currentIdx, 0, removed)
    tempSelectedColumns.value = newCols
    tempSelectedColumnProps.value = newCols.map(col => col.prop)
    dragStartY.value = e.clientY
  }
}

const stopDrag = (moveHandler?: (e: MouseEvent) => void, upHandler?: () => void) => {
  isDragging.value = false
  dragIndex.value = -1
  dragOverIndex.value = -1
  if (moveHandler) document.removeEventListener('mousemove', moveHandler)
  if (upHandler) document.removeEventListener('mouseup', upHandler)
  document.removeEventListener('mouseleave', stopDrag)
}

/** 处理搜索表单时间（保留原始） */
const handleTimeInput = (field: string, value: string) => {
  queryParams[field] = value.replace(/[^0-9]/g, '')
}

const handleTimeBlur = (field: string) => {
  const value = queryParams[field]
  if (!value) return
  if (/^\d{2}:\d{2}$/.test(value)) return
  if (value.length !==4 || !/^\d{4}$/.test(value)) {
    message.error('请输入4位数字的时间格式(HHmm)')
    queryParams[field] = ''
    return
  }
  const formatted = formatTimeString(value)
  queryParams[field] = formatted || ''
  if (!formatted) message.error('请输入有效的时间格式(HHmm)')
}

// 计算属性（保留原始）
const displayedColumns = computed<TableColumn[]>(() => [...selectedColumns.value])
const allColumnsForTransfer = computed(() =>
  allColumns.map(col => ({ key: col.prop, label: col.label }))
)

watch(tempSelectedColumnProps, () => updateTempSelectedColumns(), { deep: true })

const tableRowClassName = ({ rowData }: { rowData: any }) => {
  return rowData?.markStatus === 1 ? 'row-first' : ''
}

/** 打开数量编辑弹窗 */
const openQuantityEdit = (row: ScheduleRecordVO) => {
  // 深拷贝行数据到当前编辑对象
  currentRow.value = JSON.parse(JSON.stringify(row))
  quantityDialogVisible.value = true
}

/** 自动刷新（保留原始） */
const refreshInterval = ref(120000)
const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)
const autoRefreshEnabled = ref(true)

const startAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
  autoRefreshTimer.value = setInterval(() => getList(), refreshInterval.value)
}

const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
}

/** 初始化（保留原始） */
onMounted(async () => {
  try {
    await initColumnSettings()
    await nextTick()
    await getList()
    if (autoRefreshEnabled.value) startAutoRefresh()
  } catch (err) {
    message.error('页面初始化失败')
  }
})

onUnmounted(() => stopAutoRefresh())

// 核心：el-table-v2列配置（整合数量列）
const tableV2Columns = computed<Column<ScheduleRecordVO>[]>(() => {
  // 动态列逻辑（转换原始el-table-column配置）
  const baseColumns = displayedColumns.value.map(column => ({
    key: column.prop,
    title: column.label,
    dataKey: column.prop,
    width: column.width || 120,
    cellRenderer: ({ cellData, rowData }) => {
      const row = rowData as ScheduleRecordVO
      const cellValue = cellData?.toString() || ''
      const isDisabled = row.pstatus === 12
      // 处理新的数量复合列 - 仅显示数据，点击打开弹窗
      if (column.prop === 'quantity') {
        return (
          <div 
            style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
            onClick={() => openQuantityEdit(row)}
          >
            {/* 第一行：标题行 */}
            <div style="display: flex; font-weight: 500; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="J" placement="top">
                  <span>J</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="S" placement="top">
                  <span>S</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="G" placement="top">
                  <span>G</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="Y" placement="top">
                  <span>Y</span>
                </ElTooltip>
              </div>
            </div>
            
           
            
           
             {/* 第二行：销售数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.crewSaleQty || '-'} placement="top">
                  <span>{row.crewSaleQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.bussClassSaleQty || '-'} placement="top">
                  <span>{row.bussClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.premEcoClassSaleQty || '-'} placement="top">
                  <span>{row.premEcoClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.ecoClassSaleQty || '-'} placement="top">
                  <span>{row.ecoClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>
            </div>
             {/* 第三行：数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.crewQty || '-'} placement="top">
                  <span>{row.crewQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.bussClassQty || '-'} placement="top">
                  <span>{row.bussClassQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.premEcoClassQty || '-'} placement="top">
                  <span>{row.premEcoClassQty || '-'}</span>
                </ElTooltip>
              </div>/
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.ecoClassQty || '-'} placement="top">
                  <span>{row.ecoClassQty || '-'}</span>
                </ElTooltip>
              </div>
            </div>
          </div>
        )
      }

      if (column.editable) {
        if (isTimeColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => { row[column.prop] = val }}
              placeholder={`请输入${column.label}(HHmm)`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
              onBlur={() => handleColumnTimeBlur(row, column.prop)}
              showWordLimit
                disabled={isDisabled}
            />
          )
        }

        // 非数量列的可编辑逻辑保留
        if (!isNumberColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => { row[column.prop] = val }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onBlur={() => handleTextBlur(row, column.prop)}
              showWordLimit
                disabled={isDisabled}
            />
          )
        }
      }

      if (column.prop === 'pstatus') {
        return <ElTag type="primary">{getStatusLabel(cellData)}</ElTag>
      }
      
      // 特殊列：航空公司
      if (column.prop === 'airlineComp') {
        return h(DictTag, {
          type: DICT_TYPE.PPLAN_AIRLINE_ID,
          value: row.airlineComp
        })
      }
      
      // 特殊列：航线类型
      if (column.prop === 'airlinePattern') {
        return h(DictTag, {
          type: DICT_TYPE.PPLAN_AIRLINE_TYPE,
          value: row.airlinePattern
        })
      }
      
      // 航线列渲染（depLoc - arrLoc拼接）
      if (column.prop === 'route') {
        const depLoc = row.depLoc || ''
        const arrLoc = row.arrLoc || ''
        const routeText = depLoc && arrLoc ? `${depLoc} - ${arrLoc}` : '-'
        return (
          <ElTooltip content={routeText} placement="top">
            <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ">
              {routeText}
            </div>
          </ElTooltip>
        )
      }

      if (column.prop === 'createTime') {
        return <ElTooltip content={formatDate(cellData) || '-'}>
          <span class="flex items-center">
            <ElIcon class="mr-2"><Timer /></ElIcon>
            {formatDate(cellData) || '-'}
          </span>
        </ElTooltip>
      }

      if (isTimeColumn(column.prop)) {
        return <ElTooltip content={formatDisplayTime(cellValue) || '-'}>
          <span>{formatDisplayTime(cellValue) || '-'}</span>
        </ElTooltip>
      }

      return <span>{cellValue || '-'}</span>
    }
  }))

  // 操作列：保留原始逻辑
  const actionColumn: Column<ScheduleRecordVO> = {
    key: 'operations',
    title: '操作',
    width: 180,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as ScheduleRecordVO
      return (
        <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openForm('update', row.flightNo)}
          >
            查看详情
          </ElButton>

          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openAddForm(row.flightNo, row.recordDate)}
          >
            加餐
          </ElButton>

          <ElDropdown
            v-slots={{
              dropdown: () => (
                <ElDropdownMenu>
                  {pstatusList.map(item => (
                    <ElDropdownItem
                      key={item.value}
                      onClick={() => handleStatusChange(row, item.value)}
                    >
                      {item.label}
                    </ElDropdownItem>
                  ))}
                </ElDropdownMenu>
              )
            }}
          >
            <ElButton type="primary" link size="small">
              <ElIcon class="mr-1"><DArrowRight /></ElIcon>
              更多
            </ElButton>
          </ElDropdown>
        </div>
      )
    }
  }

  return [...baseColumns, actionColumn]
})
</script>

<style scoped>
/* 保留原始所有样式，新增文本溢出样式 */
:deep(.el-table__row.row-first),
:deep(.el-table-v2__row.row-first) {
  background-color: #f26a6e !important;
}

:deep(.el-input__inner) {
  width: 100% !important;
  min-height: 28px !important;
}
:deep(.el-table-v2__cell) {
  padding: 4px 8px !important;
}
:deep(.el-table td),
:deep(.el-table th) {
  padding: 8px 0 !important;
}

.column-setting-group {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
}
:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

.draggable-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
  padding-right: 8px;
}
.draggable-item {
  position: relative;
  user-select: none;
  transition: all 0.2s ease;
}
.draggable-item:hover {
  background-color: #f8fafc !important;
  border-color: #c0c4cc !important;
}
.draggable-item .el-icon-rank {
  cursor: grab;
  transition: all 0.2s ease;
}
.draggable-item .el-icon-rank:active {
  cursor: grabbing;
  transform: scale(1.2);
}
.draggable-item.dragging {
  opacity: 0.8;
  transform: scale(1.02);
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-table th),
:deep(.el-table-v2__header) {
  background-color: #f8fafc !important;
}
:deep(.el-input) {
  margin: 0 !important;
}

/* 文本溢出样式 */
.overflow-hidden {
  overflow: hidden;
}
.whitespace-nowrap {
  white-space: nowrap;
}
.text-ellipsis {
  text-overflow: ellipsis;
}
</style>